﻿extern alias RoutineBase1000;
extern alias RoutineBase1100;

using System;
using System.Diagnostics;
using System.IO;
using System.ServiceProcess;
using System.Timers;
using Citi.Scheduler.Domain;
//using Citi.Scheduler.WebUi.Models;
using Timer = System.Timers.Timer;
using Citi.Helpers;
using Citi.Scheduler.Domain.Utils;

namespace Citi.Scheduler.WindowsServices
{
    partial class ExecutionEngine : ServiceBase
    {
        private Timer timer = new Timer();
        private const string EventSource = "Citi Execution Engine Service";
        private const string EventLogName = "Citi Execution Engine Service Log";
        private Machine machine;

        public ExecutionEngine()
        {
            InitializeComponent();

            try
            {
                if (!EventLog.SourceExists(EventSource)) EventLog.CreateEventSource(EventSource, EventLogName);
            }
            catch
            {
            }
        }

        protected override void OnStart(string[] args)
        {
            try
            {
                //using (NetworkShareAccesser.Access(ExecutionAction.MemoryUsagePath, ExecutionAction.NetworkUser, ExecutionAction.NetWorkPassword))
                using (Citi.SecurityHelper.ImpersonateCitiUser.GetImpersonateUser(ExecutionAction.NetworkUser, ExecutionAction.NetworkUser, ExecutionAction.NetWorkPassword))
                {
                    machine = new Machine().GetByHostName(Environment.MachineName, MachineCenter.Execution);

                    if (machine == null)
                    {
                        EventLog.WriteEntry("Machine does not exist in the database or it isn't a Execution Center Machine", EventLogEntryType.Error);
                        throw new Exception("Machine does not exist in the database");
                        //return;
                    }

                    Context.ClearContext();
                    //machine.Status = (int)MachineStatus.Idle;
                    //machine.Save(machine);

                    EventLog.Log = EventLogName;
                    EventLog.Source = EventSource;
                    ExecutionAction.MachineId = machine.Id;
                    ExecutionAction.EventLog = EventLog;
                    //ExecutionAction.Machine = machine;
                    ExecutionAction.ProcessRunning = false;

                    if (!Directory.Exists(ExecutionAction.MemoryUsagePath))
                        Directory.CreateDirectory(ExecutionAction.MemoryUsagePath);

                    timer.Elapsed += TimerOnElapsed;
                    timer.Interval = 60000;
                    timer.Start();
                }
            }
            catch (Exception e)
            {
                LogUtil.PathLogErro = ExecutionAction.ErrorLog;
                LogUtil.LogError(EventLog, e);
                //File.WriteAllText(ExecutionAction.ErrorLog, "Citi Scheduler Execution Service: " + e.Message
                //    + (e.InnerException != null ? e.InnerException.Message : string.Empty) + e.StackTrace);
            }
        }

        private void TimerOnElapsed(object sender, ElapsedEventArgs elapsedEventArgs)
        {
            if (ExecutionAction.ProcessRunning) return;
            timer.Stop();
            try
            {
                ExecutionAction.StartEngine();
            }
            finally
            {
                timer.Start();
            }
        }

        protected override void OnStop()
        {
            //try
            //{
            //    //var machine = new Machine().GetByHostName(Environment.MachineName);
            //    Machine.Status = (int)MachineStatus.Stopped;
            //    Machine.Save(Machine);
            //}
            //catch { }

            ExecutionAction.SetStoppedRoutine();

            timer.Stop();
            System.Threading.Thread.Sleep(2000);
        }
    }
}
